<template>
  <div>
    <Card :bordered="false" dis-hover bordered>
      <Layout>
        <Header>
          <Row>
            <div class="search-con">
              <Input clearable placeholder="输入角色名称" @keyup.enter.native="handleSearch" class="search-input"
                     v-model="searchRoleName"/>
              <Button @click="handleSearch" class="search-btn" type="primary">
                <!--                <Icon type="search"></Icon>-->
                搜索
              </Button>
            </div>
          </Row>
        </Header>
        <Header>
          <Row>
            <Button size="default" type="default" @click="openAddModal">添加角色
            </Button>
            <Button size="default" type="error" class="space-left-mini" @click="openDeleteModal">批量删除
            </Button>
            <Button size="default" type="default" class="space-left-mini" @click="refreshNodes">刷新
            </Button>
            <Switch size="large" class="space-left-mini" v-model="openTips">
              <span slot="open">提示</span>
              <span slot="close">关闭</span>
            </Switch>
          </Row>
        </Header>
        <Content>
          <Row>
            <Alert v-if="openTips" style="height:40px" show-icon>已选择
              <span class="select-count">{{checkedNums}}</span>
              项
              <span class="clear-text " @click="clearChecked">清空</span>
            </Alert>
          </Row>
        </Content>
        <Content>
          <Row>
            <Table
              ref="roleTable"
              :loading="loading"
              width="100%"
              :height="clientHeight"
              border
              stripe
              @on-selection-change="selectedChange"
              @on-row-click="clickRow"
              :columns="roleColumns"
              :data="roleData">
              <template slot-scope="{ row }" slot="name">
                <strong>{{ row.name }}</strong>
              </template>
              <template slot-scope="{ row, index }" slot="action">
                <Button type="warning" size="small" style="margin-right: 5px" @click="openMenuAuth">菜单权限</Button>
                <Button type="default" size="small" style="margin-right: 5px" @click="openEditModal">编辑</Button>
              </template>
            </Table>
          </Row>
        </Content>
        <Footer>
          <Row>
            <Page :total="totals"
                  :page-size="pageSize"
                  class="page-right"
                  @on-change="changepage"
                  @on-page-size-change="pages"
                  show-total
                  show-sizer
                  show-elevator
                  show-total></Page>
          </Row>
        </Footer>
      </Layout>


      <!--添加角色模态框-->
      <AddForm ref="addForm"/>


      <!--编辑角色模态框-->
      <EditForm ref="editForm"/>

      <MenuAuth ref="menuAuth"/>

      <!--删除提示 模态框-->
      <Modal
        title="提示"
        v-model="deleteModal"
        class-name="vertical-center-modal">
        <p slot="header" class="delete-title">
          <Icon type="ios-information-circle"/>
          <span>删除提示</span>
        </p>
        <p class="delete-tips">确定要删除以下选中的角色?</p>
        <div class="aligin-left">
          <Tag type="dot" color="primary" v-for="tag in checkedNames">{{tag}}</Tag>
        </div>
        <div slot="footer">
          <Button type="error" size="large" long @click="deleteRoles">确定</Button>
        </div>
      </Modal>

      <!--角色树 模态框-->
      <RoleTreeModal ref="roleTreeModal"/>

      <!--部门树 模态框-->
      <DeptTreeModal ref="deptTreeModal"/>


    </Card>
  </div>
</template>

<script>
  import {getRoleList, batchDeleteNodes, getSysCodeList} from '@/api/role'
  import RoleTreeModal from './modal_roletree'
  import DeptTreeModal from './modal_depttree'
  import AddForm from './modal_addform'
  import EditForm from './modal_editform'
  import MenuAuth from './modal_menuauth'

  export default {
    name: 'rolemgt',
    components: {
      RoleTreeModal,
      DeptTreeModal,
      AddForm,
      EditForm,
      MenuAuth,
    },
    data: () => ({
      openTips: true,
      loading: false,
      searchRoleName: "",
      checkedNums: 0,
      currentIndex: 1,
      clickedRow: {},
      roleColumns: [
        {type: 'selection', width: 60, align: 'center', sortable: true},
        {title: '角色名称', key: 'name', slot: 'name', width: 271, align: 'center', sortable: true},
        {title: '别名', key: 'enname', width: 271, align: 'center', sortable: true,},
        {
          title: '数据范围', key: 'datascope', width: 120, align: 'center', sortable: true,
          render: (h, params) => {
            switch (params.row.datascope) {
              case '1':
                return h('span', '所有权限');
              case '2':
                return h('span', '其他');
              case '4':
                return h('span', '仅个人');
              default:
                return h('span', '无');
            }
          }
        },
        {title: '上级角色', key: 'pName', width: 220, align: 'center', sortable: true},
        {title: '所在部门', key: 'deptName', width: 220, align: 'center', sortable: true},
        {title: '所属系统', key: 'syscode', width: 120, align: 'center', sortable: true},
        // {title: '备注', key: 'remark', width: 220, align: 'center', sortable: true},
        {title: '操作', key: 'action', width: 300, slot: "action", align: 'center', sortable: true, fixed: 'right'}
      ],
      roleForm: {
        name: '',
        enname: '',
        parentName: '',
        datascope: '',
        deptName: '',
        num: 0,
        syscode: '',
      },
      ruleValidate: {
        name: [
          {required: true, message: '角色名称不能为空', trigger: 'blur'}
        ],
        enname: [
          {required: true, message: '角色别名不能为空', trigger: 'blur'},
        ],
        parentName: [
          {required: true, message: '上级角色不能为空', trigger: 'blur'}
        ],
        datascope: [
          {required: true, message: '数据不能为空', trigger: 'blur,change'}
        ],
        deptName: [
          {required: true, message: '部门不能为空', trigger: 'blur'}
        ],
        syscode: [
          {required: true, message: '请输入系统代码', trigger: 'blur,change'}
        ],
      },
      totals: 0,
      pageSize: 20,
      roleData: [],
      deptData: [],
      selectedRole: {},
      selectedDept: {},
      //删除
      checkedIds: [],
      checkedNames: [],
      deleteModal: false,
      clientHeight: "",
      sysList: [],
    }),
    methods: {
      /**
       * 动态监控屏幕宽高比
       */
      initClientWidth() {
        // 获取浏览器可视区域高度
        this.clientHeight = `${document.documentElement.clientHeight - 400}`;
        let _that = this;
        window.onresize = function temp() {
          _that.clientHeight = `${document.documentElement.clientHeight - 400}`;
        };
      },
      clearChecked() {
        this.$refs.roleTable.selectAll(false);
        this.checkedIds = [];
      },
      initRoleTable() {
        this.loading = true;
        let name = this.searchRoleName;
        let pageSize = this.pageSize;
        let offset = (this.currentIndex - 1) * this.pageSize;
        this.clearChecked();
        getRoleList({name, pageSize, offset}).then(res => {
          this.loading = false;
          const data = res.data;
          const message = data.message;
          const code = data.code;
          if (code === 200) {
            this.roleData = [];
            this.roleData.push(...data.data.rows);
            this.totals = data.data.total;
          }
          if (code === 500) {
            this.$Message.error(message);
          }
        }).catch(err => {
          this.loading = false;
          console.error("加载角色表格出错" + err);
        });
      },
      calcPages() {
        // const selectNums = this.checkedIds.length <= 0 ? 1 : this.checkedIds.length <= 0 ? 1 : this.checkedIds.length;
        const selectNums = this.checkedIds.length;
        const totalPage = Math.ceil((this.totals - selectNums) / this.pageSize);
        this.currentIndex = this.currentIndex > totalPage ? totalPage : this.currentIndex;
        this.currentIndex = this.currentIndex < 1 ? 1 : this.currentIndex;
      },
      refreshNodes() {
        this.initRoleTable(1);
      },
      pages(num) {
        this.pageSize = num;
        this.changepage(1);
      },
      changepage(index) {
        this.currentIndex = index;
        this.initRoleTable();
      },
      handleResult(res) {
        let data = res.data;
        let message = data.message;
        let code = data.code;
        if (code === 200) {
          this.calcPages();
          this.$Message.success(message);
          this.initRoleTable();
        }
        if (code === 500) {
          this.$Message["warning"]({background: true, content: message});
        }
      },
      handleSearch() {
        this.initRoleTable()
      },
      selectedChange: function () {
        let selectedRows = this.$refs.roleTable.getSelection();
        if (!!selectedRows) {
          this.checkedNums = selectedRows.length;
        }
      },
      openAddModal() {
        this.$refs.addForm.open = true;
        this.$refs.addForm.resetRoleForm();
        this.$refs.addForm.sysList = this.sysList;
      },
      openEditModal() {
        let _that = this;
        this.$refs.editForm.open = true;
        this.$refs.editForm.sysList = this.sysList;
        setTimeout(function () {
          //延迟打开 让table自身的 clickRow事件先执行
          _that.$refs.editForm.initRoleForm();
        }, 50);

      },
      openMenuAuth() {
        let _that = this;
        this.$refs.menuAuth.open = true;
        setTimeout(function () {
          //延迟打开 让table自身的 clickRow事件先执行
          _that.$refs.menuAuth.initMenuAuth();
        }, 50);

      },
      deleteRoles() {
        //有节点选中
        if (this.checkedIds && this.checkedIds.length > 0) {
          batchDeleteNodes(this.checkedIds.join(",")).then(res => {
            this.handleResult(res);
          }).catch(err => {
            console.error("批量删除时出现异常:" + err)
          });
          this.deleteModal = false;
        }
      },
      openDeleteModal() {
        this.checkedIds = [];
        this.checkedNames = [];
        let selectedList = this.$refs.roleTable.getSelection();
        if (selectedList !== undefined && selectedList.length > 0) {
          selectedList.forEach((item, index) => {
            this.checkedIds.push(item.id);
            this.checkedNames.push(item.name);
          });
          this.deleteModal = true;
        } else {
          this.$Message["warning"]({background: true, content: "请先选择需要删除的角色数据"});
        }
      },
      clickRow(data, index) {
        this.clickedRow = data;
      },
      initSysCodeList() {
        getSysCodeList().then(res => {
          const data = res.data;
          this.sysList = [];
          this.sysList.push(...data);
        }).catch(err => {
          console.error("获取系统代码出错")
        })
      }
    },
    mounted() {
      this.initRoleTable();
      this.initClientWidth();
      this.initSysCodeList();
    },
    computed: {}
  }
</script>

<style lang="less">
  @import 'index.less';
</style>
